Page({1
    data: {
    asd:[],
    a: false, // 控制优惠券弹出层显示
    activeTab: 'available', // 当前激活的tab
    availableCoupons: [], // 可用优惠券
    unavailableCoupons: [], // 不可用优惠券
    selectedCouponId: '', // 当前选中的优惠券ID
        checkedAddress: {
            name: '请选择收货地址',
            tel: '',
            addressDetail: ''
        },
        checkedGoodsList: [],
        money: {
            goodsTotalPrice: '0.00',
            freightPrice: '0.00',
            couponPrice: '0.00'
        },
        productIds: '',
        addressId: null,
        value: '',
        hasValidAddress: false,
        isLoading: true // 新增：加载状态
    },


  
    aaa() {
        this.setData({ a: true });
      },
    
    bbb() {
        this.setData({ a: false });
      },
    //   总
    getCheckoutData(productIds) {
        const token = wx.getStorageSync('token');

        const requestData = {
            cartId: 0,
            couponId: 0,
            userCouponId: 0,
            grouponRulesId: 0,
            productIds: productIds.join(',')
        };

        // 明确判断，只有有效的addressId才传递
        if (this.data.addressId && this.data.addressId > 0) {
            requestData.addressId = this.data.addressId;
        }

        console.log('请求结算数据参数:', requestData); // 调试日志

        wx.request({
            url: 'http://admin.bsmall.byesame.com/wx/cart/checkout',
            data: requestData,
            method: "GET",
            header: {
                'x-byesame-token': token
            },
            success: (res) => {
                console.log('结算接口返回:', res.data); // 调试日志
                if (res.data.errno === 0) {
                    const data = res.data.data;
                    const hasAddress = !!(data.checkedAddress && data.checkedAddress.id);

                    this.setData({
                        checkedAddress: data.checkedAddress || this.data.checkedAddress,
                        checkedGoodsList: data.checkedGoodsList || [],
                        money: {
                            goodsTotalPrice: this.formatPrice(data.goodsTotalPrice || 0),
                            freightPrice: this.formatPrice(data.freightPrice || 0),
                            couponPrice: this.formatPrice(data.couponPrice || 0)
                        },
                        addressId: hasAddress ? data.checkedAddress.id : this.data.addressId,
                        hasValidAddress: hasAddress,
                        isLoading: false // 关闭加载状态
                    });
                } else {
                    wx.showToast({
                        title: res.data.errmsg,
                        icon: 'error'
                    });
                    this.setData({
                        isLoading: false
                    });
                }
            },
            fail: (err) => {
                console.error('结算接口请求失败:', err);
                wx.showToast({
                    title: '网络错误',
                    icon: 'error'
                });
                this.setData({
                    isLoading: false
                });
            }
        });
    },
    //   收货地址
    handleSettle() {
        if (!this.data.hasValidAddress) {
            wx.showToast({
                title: '请选择收货地址',
                icon: 'none'
            });
            return;
        }

        const token = wx.getStorageSync('token');
        wx.request({
            url: 'http://admin.bsmall.byesame.com/wx/order/submit',
            method: 'POST',
            header: {
                'x-byesame-token': token,
                'content-type': 'application/json'
            },
            data: {
                addressId: this.data.addressId,
                cartId: "0",
                couponId: "0",
                grouponLinkId: 0,
                grouponRulesId: 0,
                message: this.data.value,
                userCouponId: this.data.selectedCouponId || "0", // 传递选中的优惠券ID
                productIds: this.data.productIds
            },
            success: (res) => {
                console.log('提交订单返回:', res.data); // 调试日志
                if (res.data.errno === 0) {
                    const orderId = res.data.data.orderId;
                    wx.navigateTo({
                        url: `../payment/payment?orderId=${orderId}`
                    });
                } else {
                    wx.showToast({
                        title: res.data.errmsg,
                        icon: 'error'
                    });
                }
            },
            fail: (err) => {
                console.error('提交订单失败:', err);
                wx.showToast({
                    title: '提交订单失败',
                    icon: 'error'
                });
            }
        });
    },
// Tab切换事件
onTabChange(event) {
    this.setData({ activeTab: event.detail });
  },
  
  // 选择优惠券事件
  selectCoupon(event) {
    const couponId = event.detail.id;
    this.setData({ selectedCouponId: couponId });
  },
  
  // 取消使用优惠券
  cancelCoupon() {
    this.setData({ selectedCouponId: null });
    this.bbb(); // 关闭弹窗
  },
    formatPrice(price) {
        return parseFloat(price || 0).toFixed(2);
    },

    address() {
        // 传递当前地址ID，如果是null则传0
        const currentAddressId = this.data.addressId || 0;
        wx.navigateTo({
            url: `/pages/address/address?currentAddressId=${currentAddressId}`
        });
    },
    //   优惠卷
    youhui() {
        const token = wx.getStorageSync('token');
        this.setData({ isLoading: true });
        
        wx.request({
          url: 'http://admin.bsmall.byesame.com/wx/coupon/selectlist',
          data: {
            cartId: 0,
            grouponRulesId: 0
          },
          header: {
            'x-byesame-token': token
          },
          method: "GET",
          success: (res) => {
            console.log("优惠卷", res);
            
            if (res.data && res.data.data && res.data.data.list) {
              const coupons = res.data.data.list;
              
              // 过滤可用和不可用优惠券
              const available = [];
              const unavailable = [];
              
              coupons.forEach(coupon => {
                // 简单判断是否可用（实际逻辑需要根据业务规则调整）
                const isAvailable = this.isCouponAvailable(coupon);
                if (isAvailable) {
                  available.push(coupon);
                } else {
                  unavailable.push(coupon);
                }
              });
              
              this.setData({
                availableCoupons: available,
                unavailableCoupons: unavailable
              });
            }
          },
          fail: () => {
            wx.showToast({
              title: '获取优惠券失败',
              icon: 'none'
            });
          },
          complete: () => {
            this.setData({ isLoading: false });
          }
        });
      },
    
    onChange(event) {
        this.setData({
            value: event.detail
        });
    },

    onLoad(options) {
        const productIds = options.productIds ? options.productIds.split(',').map(id => parseInt(id)) : [];
        this.setData({
            productIds: productIds.join(','),
            addressId: null // 明确设置为null
        });
        console.log('结算页加载，productIds:', productIds); // 调试日志
        this.youhui()
        // 添加延时器，确保页面稳定加载
        setTimeout(() => {
            this.getCheckoutData(productIds);
        }, 200);
    },

    onShow() {
        // 从地址页返回时检查是否有选中的地址
        const selectedAddressId = wx.getStorageSync('selectedAddressId');
        if (selectedAddressId) {
            this.setData({
                addressId: selectedAddressId,
                hasValidAddress: true
            });
            wx.removeStorageSync('selectedAddressId'); // 清除临时存储
        }

        const productIds = this.data.productIds.split(',').map(id => parseInt(id));
        console.log('结算页显示，重新获取数据'); // 调试日志

        // 添加延时器，确保页面切换完成
        setTimeout(() => {
            this.getCheckoutData(productIds);
        }, 300);
    },

    onReady() {
        // 页面渲染完成时的额外保障
        setTimeout(() => {
            if (this.data.isLoading) {
                console.log('页面已准备就绪，等待数据加载...');
            }
        }, 300);
    }
});